<template>
	<div>
		<div class="panel edit-panel" v-show="que.editing">
			<validator :name="validatorName">
			<div class="panel-body">
				<div class="box-title" :class="{handle: que.que_id}">
					<span class="que-title">{{ que.que_num + "、" + TYPETEXT[que.que_type] }}</span>
					<span>分值</span>
					<input type="text" class="que-score que-area" 
						v-model="que.que_score"
						v-validate:score="formFileds.score.validate">
					<div class="edit-btn-group pull-right" v-if="que.que_id">
						<!-- <a href="javasript:;" title="上移" v-on:click="moveUp($index)"><span class="glyphicon glyphicon-menu-up"></span></a>
						<a href="javasript:;" title="下移" v-on:click="moveDown($index)"><span class="glyphicon glyphicon-menu-down"></span></a> -->
						<a href="javasript:;" title="删除" v-on:click="delQue()">
							<span class="glyphicon glyphicon-trash"></span>
						</a>
					</div>
				</div>
				<div class="box-body">
					<!-- <textarea type="text" class="que-area que-content" rows="1" 
						:placeholder="formFileds.content.placeholder" 
						v-model="que.que_content"
						v-validate:content="formFileds.content.validate"></textarea> -->
					<div :id="'content'+index" class=""></div>
					<template v-if="que.que_type==0">
						<div class="radio" v-for="item in que.que_items">
							<label><input type="radio" 
								:name="'edit'+que.que_num" 
								:value="$index" 
								v-model="que.que_answer"
								v-validate:answer="formFileds.answer.validate">{{ item }}</label>
						</div>
					</template>
					<template v-if="que.que_type==1">
						<div class="radio" v-for="item in que.que_items" track-by="$index">
							<label><input type="radio" 
								v-bind:name="'edit'+que.que_num" 
								v-bind:value="$index" 
								v-model="que.que_answer"
								v-validate:answer="formFileds.answer.validate">
								{{ OPTIONTEXT[$index] }}、
							</label>
							<!-- <textarea class="que-area que-item" type="text" rows="1" :placeholder="formFileds.items.placeholder" lazy
								v-model="item"
								:field="'item-content'+$index"
								v-validate="formFileds.items.validate"></textarea> -->
							<div :id="'item'+$index+'-'+index" class="que-item"></div>
							<a class="del-item pull-right" href="javasript:;" title="删除" v-on:click="delItem($index)"><span class="glyphicon glyphicon-remove"></span></a>
						</div>
						<a href="javascript:;" v-on:click="appendItem(que.que_items)">添加新选项</a>
					</template>
					<template v-if="que.que_type==2">
						<div class="checkbox" v-for="item in que.que_items" track-by="$index">
							<label><input type="checkbox" 
								v-bind:name="'edit'+que.que_num" 
								v-bind:value="$index+''" 
								v-model="que.que_answer"
								v-validate:answer="formFileds.answer.validate">
								{{ OPTIONTEXT[$index] }}、
							</label>
							<!-- <textarea class="que-area que-item" type="text" rows="1" :placeholder="formFileds.items.placeholder" lazy
								v-model="item"
								:field="'item-content'+$index"
								v-validate="formFileds.items.validate"></textarea> -->
							<div :id="'item'+$index+'-'+index" class="que-item"></div>
							<a class="del-item pull-right" href="javasript:;" title="删除" v-on:click="delItem($index)"><span class="glyphicon glyphicon-remove"></span></a>
						</div>
						<a href="javascript:;" v-on:click="appendItem(que.que_items)">添加新选项</a>
					</template>
					<template v-if="que.que_type==3">
						<div v-q-textarea="que.que_answer" class="que-area que-content" contenteditable="true" :placeholder="formFileds.answer.placeholder"></div>
						<textarea type="text" class="que-area que-content" rows="1" :placeholder="formFileds.answer.placeholder" 
							v-model="que.que_answer" 
							v-validate:answer="formFileds.answer.validate"
							></textarea>
					</template>
					<template v-if="que.que_type==4">
						<div v-q-textarea="que.que_answer" class="que-area que-content" contenteditable="true" :placeholder="formFileds.answer.placeholder"></div>
						<textarea type="text" class="que-area que-content" rows="1" :placeholder="formFileds.answer.placeholder" 
							v-model="que.que_answer" 
							></textarea>
					</template>
				</div>
			</div>
			</validator>
			<div class="panel-footer clearfix">
				<button class="btn btn-primary pull-right" v-on:click="saveQue()">保存</button>
				<button class="btn btn-default pull-right" v-on:click="cancelEdit()">取消</button>
			</div>
		</div>
		<div class="panel display-panel" v-else v-on:click="showEdit($event)">
			<div class="panel-body">
				<div class="box-title handle">
					<span class="que-title">{{ que.que_num + "、" + TYPETEXT[que.que_type] }}</span>
					<span>分值 {{ que.que_score }}</span>
					<div class="edit-btn-group pull-right">
						<!-- <a href="javasript:;" title="上移" v-on:click="moveUp($index)"><span class="glyphicon glyphicon-menu-up"></span></a>
						<a href="javasript:;" title="下移" v-on:click="moveDown($index)"><span class="glyphicon glyphicon-menu-down"></span></a> -->
						<a href="javasript:;" title="删除" v-on:click="delQue()">
							<span class="glyphicon glyphicon-trash"></span>
						</a>
					</div>
				</div>
				<div class="box-body">
					<p>{{{ que.que_content }}}</p>
					<template v-if="que.que_type==0">
						<div class="radio" v-for="item in que.que_items">
						<label><input type="radio" v-bind:name="'display'+que.que_num" v-bind:value="$index" v-model="que.que_answer">{{ item }}</label>
					</div>
					</template>
					<template v-if="que.que_type==1">
						<div class="radio" v-for="item in que.que_items" track-by="$index">
							<label><input type="radio" v-bind:name="'display'+que.que_num" v-bind:value="$index" v-model="que.que_answer">
								{{ OPTIONTEXT[$index] }}、 
							</label>
							<div class="display-item">{{{ item }}}</div>
						</div>
					</template>
					<template v-if="que.que_type==2">
						<div class="checkbox" v-for="item in que.que_items" track-by="$index">
							<label><input type="checkbox" v-bind:name="'display'+que.que_num" v-bind:value="$index+''" v-model="que.que_answer">
								{{ OPTIONTEXT[$index] }}、
							</label>
							<div class="display-item">{{{ item }}}</div>
						</div>
					</template>
					<template v-if="que.que_type==3">
						<p>{{ que.que_answer }}</p>
					</template>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		ready: function() {
			if (!this.que.que_id) {
				var option = Object.assign({}, this.contentOption)
				if (this.que.que_type == 3) {
					option.placeholder = '请输入题干，请使用两个下划线代替需要填空的空格，且只能有一个空'
				}
				$('#content'+this.index).summernote(option);
				if (this.que.que_type == 1 || this.que.que_type == 2) {
					this.que.que_items.forEach((value, index) => {
						$('#item'+index+'-'+this.index).summernote(this.itemOption).summernote('code', '');
					})
				}
			}
		},
		props: ['que', 'index'],
		data() {
			return {
				TYPETEXT : ["判断题", "单选题", "多选题", "填空题", "简答题"],
                OPTIONTEXT: ['A','B','C','D','E','F','G','H'],
                validatorName: 'queVali',
                formFileds: {
                	score: {
                		placeholder: "请输入题目分值",
                		validate: {
							required: {rule: true, message: '请输入题目分值'},
							min: {rule: 1, message: '请输入在1到100之间的分值'},
							max: {rule: 100, message: '请输入在1到100之间的分值'}
                		}
                	},
                	content: {
                		placeholder: "请输入题干",
                		validate: {
							required: {rule: true, message: '请输入题干'}
                		}
                	},
                	answer: {
                		placeholder: '请输入参考答案'
                	},
                	items: {
                		placeholder: '请填写选项内容',
                		validate: {
                			required: {rule: true, message: '请填写选项内容'}
                		}
                	}
                },
                contentOption: {
                	lang: 'zh-CN',
                	placeholder: '请输入题干',
                	toolbar: [
                	    ['style', ['bold', 'italic', 'underline', 'strikethrough', 'style']],
                	    ['font', ['superscript', 'subscript']],
                	    ['fontsize', ['fontsize']],
                	    ['color', ['color']],
                	    ['para', ['ul', 'ol', 'paragraph']],
                	    ['Insert', ['picture']]
                	  ],
                	  callbacks: {
                	      onImageUpload: function(files) {
                	      	// waite for qiniu uploader
                	      	
                	        $summernote.summernote('insertImage', url);
                	      }
                	    }
                },
                itemOption: {
                	lang: 'zh-CN',
                	airMode: true,
                	popover: {
                	  air: [
                	    ['style', ['bold', 'italic', 'underline', 'strikethrough', 'style']],
                	    ['font', ['superscript', 'subscript']],
                	    ['para', ['paragraph']],
                	    ['Insert', ['picture']]
                	  ]
                	}
                }
			}
		},
		methods: {
			saveQue: function() {
				var summertContent = $('#content'+this.index);
				if (summertContent.summernote('isEmpty')) {
					this.$dispatch('msg', '请输入题干');
					return;
				} else {
					this.que.que_content = $('#content'+this.index).summernote('code');
					if (this.que.que_type == 3) {
						if (this.que.que_content.indexOf('__') < 0) {
							this.$dispatch('msg', '请输入两个下划线作为空格');
							return;
						}
						var tmp = this.que.que_content.slice(this.que.que_content.indexOf('__') + 2);
						if (tmp.indexOf('__') > -1) {
							this.$dispatch('msg', '不能输入多于两个空格');
							return;
						}
						console.log(tmp)
					}
				}

				if (this.que.que_type == 1 || this.que.que_type == 2) {
					var isValid = this.que.que_items.every((value, index) => {
						var summertItem = $('#item'+index+'-'+this.index);
						if (summertItem.summernote('isEmpty')) {
							this.$dispatch('msg', '请填写选项内容');
							return false;
						} else {
							this.que.que_items.$set(index, $('#item'+index+'-'+this.index).summernote('code'));
							return true;
						}
					});
					if (!isValid) return;
				}
				// 简答题没有分值限制
				if (!this['$'+this.validatorName].errors || this['$'+this.validatorName].errors[0].field === 'score' && this.que.que_type == 4) {
					this.$dispatch('save-que', this.index);
				} else {
					this.$dispatch('msg', this['$'+this.validatorName].errors[0].message);
					return;
				}

				this.destroySummer();
			},
			showEdit: function(event) {
				if (event.target && event.target.tagName.toLowerCase() == "span") 
					return;
				var option = Object.assign({}, this.contentOption)
				if (this.que.que_type == 3) {
					option.placeholder = '请输入题干，请使用两个下划线代替需要填空的空格，且只能有一个空'
				}
				$('#content'+this.index).summernote(option);
				$('#content'+this.index).summernote('code', this.que.que_content);
				this.que.que_items.forEach((value, index) => {
					$('#item'+index+'-'+this.index).summernote(this.itemOption);
					$('#item'+index+'-'+this.index).summernote('code', value);
				})
				this.que.editing = true;
				// 上传到七牛
				var index = this.index;
				var vm = this;
				var isInitial = false;
				var FileFormGroup = $('#content' + index + ' + .panel .note-group-select-from-files');
				FileFormGroup.find('input').remove()
				FileFormGroup.append('<button class="btn btn-default btn-sm file-picker">选择图片</button>' + 
					'<div class="progress-bar progress-bar-success file-bar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>');
				$('#content'+this.index + ' + .note-editor .note-Insert .btn').click(function() {
					if (isInitial) return;
					isInitial = true;

					var uploader = Qiniu.uploader({
		      	        runtimes: 'html5,flash,html4',
		      	        browse_button: $('#content' + index + ' + .panel .note-group-select-from-files .file-picker')[0], 
		      	        uptoken_url: '/question/getToken', 
		      	        get_new_uptoken: false,
		      	        domain: '7xs2nw.com1.z0.glb.clouddn.com/', //bucket 域名，下载资源时用到，**必需**
		      	        // container: document.getElementsByClassName('modal-content')[1],
		      	        max_file_size: '10mb',
		      	        flash_swf_url: 'plupload/Moxie.swf', //引入flash,相对路径
		      	        max_retries: 3, //上传失败最大重试次数
		      	        dragdrop: true, //开启可拖曳上传
		      	        drop_element: FileFormGroup[0],
		      	        chunk_size: '4mb', 
		      	        auto_start: true, 
		      	        filters: {
		      	          mime_types : [
		      	            { title : "Image files", extensions : "jpg, gif, png" }
		      	          ]
		      	        },
		      	        init: {
		      	            'UploadProgress': function(up, file) {
		      	            	FileFormGroup.find('.file-bar').css({width: file.percent + '%'}).html(file.percent + '%');
		      	                FileFormGroup.find('.file-picker').prop('disabled', true).html('图片上传中...');
		      	            },
		      	            'FileUploaded': function(up, file, info) {
		      	                FileFormGroup.find('.file-picker').prop('disabled', false).html('选择图片');
		      	            	FileFormGroup.find('.file-bar').css({width: 0}).html('0%');
		      	                var res = JSON.parse(info);
		      	                var imgUrl = up.getOption('domain') + res.key;
		      	            	vm.uploadImgCallBack(imgUrl, res.key)
		      	            },
		      	            'Error': function(up, err, errTip) {
		      	                FileFormGroup.find('.file-picker').prop('disabled', false).html('选择图片');
		      	            	FileFormGroup.find('.file-bar').css({width: 0}).html('失败');
		      	            }
		      	        }
		      	    });
				})
			},
			delQue: function() {
				this.$dispatch('del-que');
			},
			cancelEdit: function() {
				this.$dispatch('cancel-edit');
				this.destroySummer();
			},
			appendItem: function() {
				if (this.que.que_items.length >= 8) {
					this.$dispatch('msg', '不能超过八个选项');
				} else {
					this.que.que_items.push('');
					this.$nextTick(function() {
						$('#item'+(this.que.que_items.length-1)+'-'+this.index).summernote(this.itemOption).summernote('code', '');
					})
				}
			},
			delItem: function(index) {
				if (this.que.que_items.length <= 2) {
					this.$dispatch('msg', '至少需要两个选项');
					return;
				}
				//$('#item'+(index)+'-'+this.index).summernote('destroy');
				if (this.que.que_type == 1)
					this.que_answer = -1;
				else if (this.que.que_type == 2)
					this.que.que_answer = [];

				this.que.que_items.splice(index, 1);
				this.que.que_items.forEach((value, index) => {
					$('#item'+index+'-'+this.index).summernote('code', value);
				})
			},
			destroySummer: function() {
				$('#content'+this.index).summernote('destroy');
				if (this.que.que_type == 1 || this.que.que_type == 2) {
					this.que.que_items.forEach((value, index) => {
						$('#item'+index+'-'+this.index).summernote('destroy');
					})
				}
			},
			uploadImgCallBack: function(url,fileName) {
		      	$('#content' + this.index + '+ .note-editor .modal').modal('hide');
				$('#content'+this.index).summernote('insertImage', 'http://' + url, fileName);
			}
		}
	}
</script>

<style>
	.note-group-select-from-files {
		overflow: hidden;
	}
	.file-picker {
		display: block;
	}
	.file-bar {
		min-width: 2em;
		margin-top: .5em;
	}
</style>